#include "main.h"

enum
{
	L = 0x1,
	C,
};

typedef struct
{
	int type;
	char name[N];
	char text[M];
}MSG;

#define LEN sizeof(MSG)
int main(int argc, const char *argv[])
{
	int sockfd;
	struct sockaddr_in serveraddr;
	MSG msg;
	pid_t pid;
	socklen_t len = sizeof(struct sockaddr);
	
	if(argc != 3)
	{
		printf("user:%s ip port",argv[0]);
		return -1;
	}
	// 绑定套接字
	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("socket err");
		exit(-1);
	}
	//  指定服务器地址
	 bzero(&serveraddr,len);
	 serveraddr.sin_family = AF_INET;
	 serveraddr.sin_port = htons(atoi(argv[2]));
	 serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
	 
	 // 输入用户名，并发给服务器信息
	 puts("==================client login=================");
	 msg.type = L;
	 printf("please input name"); 
     gets(msg.name);
	 sendto(sockfd, &msg ,LEN , 0 , (struct sockaddr *)& serveraddr ,len);
	 
	 // fork -- 子进程发送 ，父进程接收
	 pid = fork();
	 if(pid < 0)
	 {
		 perror("error fork");
		 exit(-1);
	 }else if (pid == 0)
	 {
		 while(1)
		 {
			 gets(msg.text);
			 msg.type = C;
			 sendto(sockfd, &msg, LEN , 0 , (struct sockaddr *)&serveraddr , len);			 
		 }		 
	 }
	 else
	 {
		 while(1)
		 {
			 recvfrom(sockfd , &msg ,LEN , 0 , (struct sockaddr *)&serveraddr ,&len );
			 puts(msg.text);
		 } 
	 }	 
}